package com.currency.mall.ui.main.optional;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.adapter.GoldRateTermAdapter;
import com.currency.mall.entity.SharesBean;
import com.currency.mall.entity.SharesRoyalty;
import com.currency.mall.entity.UserAccoutBean;
import com.currency.mall.event.MainEvent;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.ui.main.MainActivity;
import com.currency.mall.ui.my.recharge.RechargeActivity;
import com.currency.mall.ui.web.WebViewActivity;
import com.currency.mall.util.BigDecimalUtil;
import com.currency.mall.util.MD5Util;
import com.currency.mall.util.TimeUtil;
import com.currency.mall.util.Util;
import com.currency.mall.widget.MyRadioGroup;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.commonbusines.entity.ResponseBean;
import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/22.
 */

public class OptionalDetailsActicity extends BaseActivity {
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_tile)
    RelativeLayout rlTile;
    @BindView(R.id.account_balance_text)
    TextView accountBalanceText;
    @BindView(R.id.tv_account_balance)
    TextView tvAccountBalance;
    @BindView(R.id.tv_account_available_balance)
    TextView tvAccountAvailableBalance;
    @BindView(R.id.tv_principal)
    TextView tvprincipal;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.et_input_principal)
    EditText etInputprincipal;
    @BindView(R.id.tv_recommend)
    TextView tvRecommend;
    @BindView(R.id.tv_option_term)
    TextView tvOptionTerm;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_option_type)
    TextView tvOptionType;
    @BindView(R.id.tv_start_price)
    TextView tvStartPrice;
    @BindView(R.id.tv_gold_rate)
    TextView tvGoldRate;
    @BindView(R.id.tv_rights_text)
    TextView tvRightsText;
    @BindView(R.id.tv_rights)
    TextView tvRights;
    @BindView(R.id.cb_agreement)
    CheckBox cbAgreement;
    @BindView(R.id.tv_Agree)
    TextView tvAgree;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.btn_subscribe)
    Button btnSubscribe;
    @BindView(R.id.rb_50)
    RadioButton rb50;
    @BindView(R.id.rb_80)
    RadioButton rb80;
    @BindView(R.id.rb_100)
    RadioButton rb100;
    @BindView(R.id.rb_120)
    RadioButton rb120;
    @BindView(R.id.rb_150)
    RadioButton rb150;
    @BindView(R.id.rb_200)
    RadioButton rb200;
    @BindView(R.id.radioGroup)
    MyRadioGroup radioGroup;
    @BindView(R.id.rv_gold_rate)
    RecyclerView rvGoldRate;
    private SharesBean.SharesInfo sharesInfo;
    private ArrayList<SharesRoyalty> sharesRoyalties;
    private int principal =500000;
    private GoldRateTermAdapter mGoldRateTermAdapter;
    private String goldRate;//权利金率
    private String royalty;//权利金
    private String floatAccountAvailable;//可用余额
    private String royaltyType ;
    private String royaltyVal;
    private boolean isCheckedAgreement;//同意协议
    private Dialog pwdDilaog,rechargeDialogShow;
    private EditText etPwd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_optional_details);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        sharesInfo = (SharesBean.SharesInfo) getIntent().getSerializableExtra("sharesInfo");
        sharesRoyalties = getIntent().getParcelableArrayListExtra("sharesRoyalties");
        init();
    }

    private void init() {
        etInputprincipal.setText((int)principal+"");
        etInputprincipal.setSelection(etInputprincipal.getText().toString().length());
        tvTitle.setText(sharesInfo.getName()+"("+sharesInfo.getCode()+")");
        goldRate =BigDecimalUtil.mul(sharesRoyalties.get(0).getRate(),"0.01",4);
        tvGoldRate.setText(sharesRoyalties.get(0).getRate()+"%");
        tvRights.setText(Util.formatTosepara(Double.parseDouble(BigDecimalUtil.mul("500000",goldRate,2)))+ " 元");
        royalty = BigDecimalUtil.mul("500000",goldRate,2);
        royaltyType = sharesRoyalties.get(0).getType();
        royaltyVal = sharesRoyalties.get(0).getVal();
        if("DAY".equals(sharesRoyalties.get(0).getType())){
            tvEndTime.setText(TimeUtil.addTime("DAY",Integer.parseInt(sharesRoyalties.get(0).getVal())));
        }else  if("WEEK".equals(sharesRoyalties.get(0).getType())){
            tvEndTime.setText(TimeUtil.addTime("WEEK",Integer.parseInt(sharesRoyalties.get(0).getVal())));
        }else  if("MONTH".equals(sharesRoyalties.get(0).getType())){
            tvEndTime.setText(TimeUtil.addTime("MONTH",Integer.parseInt(sharesRoyalties.get(0).getVal())));
        }
        etInputprincipal.addTextChangedListener(textWatcher);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        tvStartTime.setText(df.format(new Date()));
        getUserAccount();
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_50:
                        principal = 500000;
                        break;
                    case R.id.rb_80:
                        principal = 800000;
                        break;
                    case R.id.rb_100:
                        principal = 1000000;
                        break;
                    case R.id.rb_120:
                        principal = 1200000;
                        break;
                    case R.id.rb_150:
                        principal = 1500000;
                        break;
                    case R.id.rb_200:
                        principal = 2000000;
                        break;

                }

                etInputprincipal.setText((int)principal+"");

                tvRights.setText(Util.formatTosepara(Double.parseDouble(BigDecimalUtil.mul(principal+"",goldRate,2))) + " 元");
                royalty =  BigDecimalUtil.mul(principal+"",goldRate,2);
                etInputprincipal.setSelection(etInputprincipal.getText().toString().length());

            }
        });

        rvGoldRate.setLayoutManager(new GridLayoutManager(getContext(),3));
        rvGoldRate.setNestedScrollingEnabled(false);

        mGoldRateTermAdapter = new GoldRateTermAdapter(sharesRoyalties, getContext());
        mGoldRateTermAdapter.setSelectedIndex(0);
        rvGoldRate.setAdapter(mGoldRateTermAdapter);
        mGoldRateTermAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SharesRoyalty sharesRoyalty = sharesRoyalties.get(position);
                mGoldRateTermAdapter.setSelectedIndex(position);
                royaltyType = sharesRoyalty.getType();
                royaltyVal = sharesRoyalty.getVal();
                tvGoldRate.setText(sharesRoyalty.getRate()+"%");
                goldRate = BigDecimalUtil.mul(sharesRoyalty.getRate(),"0.01",4);
                tvRights.setText(Util.formatTosepara(Double.parseDouble( BigDecimalUtil.mul(principal+"",goldRate,2))) + " 元");
                royalty =  BigDecimalUtil.mul(principal+"",goldRate,2);
                if("DAY".equals(sharesRoyalty.getType())){
                    tvEndTime.setText(TimeUtil.addTime("DAY",Integer.parseInt(sharesRoyalty.getVal())));
                }else  if("WEEK".equals(sharesRoyalty.getType())){
                    tvEndTime.setText(TimeUtil.addTime("WEEK",Integer.parseInt(sharesRoyalty.getVal())));
                }else  if("MONTH".equals(sharesRoyalty.getType())){
                    tvEndTime.setText(TimeUtil.addTime("MONTH",Integer.parseInt(sharesRoyalty.getVal())));
                }
            }
        });

        cbAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        isCheckedAgreement = true;
                    }else{
                        isCheckedAgreement = false;
                    }
            }
        });
    }


    private boolean getRadioButtonChecked(float principal){
        if(principal == 500000){
            return  true;
        }else  if(principal == 800000){
            return  true;
        }else if(principal == 1000000){
            return  true;
        }else if(principal == 1200000){
            return  true;
        }else if(principal == 1500000){
            return  true;
        }else if(principal == 2000000){
            return  true;
        }
        return  false;
    }

    private void setRadioButtonChecked(){
        rb50.setChecked(false);
        rb80.setChecked(false);
        rb100.setChecked(false);
        rb120.setChecked(false);
        rb150.setChecked(false);
        rb200.setChecked(false);
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
//            setRadioButtonChecked();
        }

        @Override
        public void afterTextChanged(Editable s) {
            if(!TextUtils.isEmpty(etInputprincipal.getText().toString())){
                tvRights.setText(Util.formatTosepara(Double.parseDouble(BigDecimalUtil.mul(etInputprincipal.getText().toString(),goldRate,2))) + " 元");
                principal = Integer.parseInt(etInputprincipal.getText().toString());
                if(!getRadioButtonChecked(principal)){
                    setRadioButtonChecked();
                }
            }
        }
    };



    public void getUserAccount() {
        NetWork.getUserApi().accountQuery()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserAccoutBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(UserAccoutBean userAccoutBean) {
                        if (userAccoutBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            tvAccountBalance.setText(Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getTotalSum())));
                            tvAccountAvailableBalance.setText("可用" + Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getUsabSum())) + " ，" + "冻结" + Util.formatTosepara(Double.parseDouble(userAccoutBean.getUserAccount().getFreezeSum())));
                            floatAccountAvailable = userAccoutBean.getUserAccount().getUsabSum();
                        } else {
                            ToastUitl.show(userAccoutBean.getMsg(), 200);
                        }
                    }
                });
    }



    public void orderSubmit() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("sharesName", sharesInfo.getName());
        hashMap.put("sharesCode", sharesInfo.getCode());
        hashMap.put("royaltyType", royaltyType);
        hashMap.put("royaltyVal", royaltyVal);
        hashMap.put("nameSum", principal);
        hashMap.put("password", MD5Util.toMD5(etPwd.getText().toString()).toLowerCase());
        NetWork.getOderApi().createOrder(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUitl.show(e.getMessage(), 200);
                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        if (responseBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            startActivity(new Intent(getContext(), MainActivity.class));
                            EventBus.getDefault().post(new MainEvent(MainEvent.TAB_ORDER));
                            ToastUitl.show("委托认购成功", 200);

                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }
                    }
                });
    }

    private void pwdDilaogShow() {
        pwdDilaog = new Dialog(getContext(), R.style.dialog);
        pwdDilaog.setContentView(R.layout.dialog_set_pwd);
        pwdDilaog.show();
        pwdDilaog.setCancelable(false);
        etPwd = (EditText) pwdDilaog.findViewById(R.id.et_input_pwd);
        Button okBtn = pwdDilaog.findViewById(R.id.bt_ok);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdDilaog.dismiss();
                orderSubmit();

            }
        });
        Button cancleBtn = pwdDilaog.findViewById(R.id.bt_cancle);
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdDilaog.dismiss();
            }
        });
    }

    private void rechargeDialogShow() {
        rechargeDialogShow = new Dialog(getContext(), R.style.dialog);
        rechargeDialogShow.setContentView(R.layout.dialog_not_title);
        rechargeDialogShow.show();
        rechargeDialogShow.setCancelable(false);
       TextView tvInfo = (TextView) rechargeDialogShow.findViewById(R.id.tv_info);
        tvInfo.setText("当前可用余额不足，是否立即充值");
        Button okBtn = rechargeDialogShow.findViewById(R.id.bt_ok);
        okBtn.setText("去充值");
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rechargeDialogShow.dismiss();
                toRecharge();
            }
        });
        Button cancleBtn = rechargeDialogShow.findViewById(R.id.bt_cancle);
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rechargeDialogShow.dismiss();
            }
        });
    }

    private void toRecharge(){
        startActivity(new Intent(getContext(), RechargeActivity.class));
    }

    @OnClick({R.id.ll_back, R.id.btn_subscribe,R.id.tv_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.btn_subscribe:
                if(isCheckedAgreement){
                    if(Integer.parseInt(etInputprincipal.getText().toString())>2000000 || Integer.parseInt(etInputprincipal.getText().toString())< 500000){
                        ToastUitl.show("名义本金必：50万-200万",200);
                    }else{
                        if(BigDecimalUtil.compare(royalty ,floatAccountAvailable)){
                            rechargeDialogShow();
                        }else{
                            pwdDilaogShow();
                        }
                    }

                }else{
                    ToastUitl.show("请勾选用户协议",200);
                }
                break;
            case R.id.tv_agreement:
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("ExtraWebPath", "http://150.109.125.51/help/guide/agreement.html");
                intent.putExtra("ExtraWebTitle", "个股场外期权委托投资合作协议");
                startActivity(intent);
                break;
        }
    }
}
